#!/bin/bash

function usage()
{
  echo "Usage: $0 target ld_address"
  echo "       target: ram -- the image will be loaded to RAM and run, the application must be built with ram link file"
  echo "               flash -- the image will be run on flash directly, the application must be build with flash link file"
  echo "               sd -- the image will be loaded from SD to RAM and run, the application must be build with ram link file"
  echo "       ld_address: ld address"
  echo "Example: $0 sd 0x87800000"
}

# 判断是否以root权限运行,防止出现危险
CUR_USER=$(env | grep USER | cut -d "=" -f 2)
if [ $CUR_USER == "root" ]; then
	echo -e "\033[31mThe CUR_USER is $CUR_USER. Please run the script with a normal user.\033[0m"
	exit 1
fi 

# 判断参数是否是2个
if [ "$#" -ne 2 ]; then
  usage $0
  exit 1
fi

# 判断系统选择可执行文件
SYSTEM=`uname -s`
if [ $SYSTEM == "Linux" ]; then
    DCD_BUILDER=dcdgen.bin
    IMG_BUILDER=imgutil.bin
else
    echo "not support!"
    exit 1
fi

# 判断两个文件是否有执行权限
if [ ! -x "../bin/$DCD_BUILDER" ]; then
	chmod +x $DCD_BUILDER
fi

if [ ! -x "../bin/$IMG_BUILDER" ]; then
	chmod +x $IMG_BUILDER
fi

# 生成DCD数据文件
../bin/$DCD_BUILDER dcd.config dcd.bin

# 制作IMG文件,不是很明白这里的几个参数都是代表什么，测试了一下编译的时候用0x87800000的话，这里参数默认也可以正常跑
if [ "$1" == "ram" ]; then
    ../bin/$IMG_BUILDER --combine base_addr=0x80000000 ivt_offset=0x1000 app_offset=0x2000 dcd_file=dcd.bin app_file=sdk20-app.bin ofile=sdk20-app.img image_entry_point=0x80002000
elif [ "$1" == "flash" ]; then
    ../bin/$IMG_BUILDER --combine base_addr=0x60000000 ivt_offset=0x1000 app_offset=0x2000 dcd_file=dcd.bin app_file=sdk20-app.bin ofile=sdk20-app.img image_entry_point=0x60002000
elif [ "$1" == "sd" ]; then
    ../bin/$IMG_BUILDER --combine base_addr=0x80000000 ivt_offset=0x400 app_offset=0x2000 dcd_file=dcd.bin app_file=sdk20-app.bin ofile=sdk20-app.img image_entry_point=$2
else
    echo "Unsupported target $1"
    usage $0
fi
